package com.syni.mdd.yhd.common.all.aop;

import com.syni.mdd.sjb.common.component.utils.common.utils.RequestHeaderData;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.annotations.EntranceCheck;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dto.requestDto.BaseReDto;
import com.syni.mdd.yhd.common.all.entity.BmsDxClientRole;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.service.BmsDxClientRoleService;
import com.syni.mdd.yhd.common.all.utils.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @className CheckParamsAspect
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/25 17:23
 * @VERSION 1.0
 **/
@Aspect
@Order(2)
@Component
public class EntranceCheckAspect {
    private final Logger log = LoggerFactory.getLogger(getClass());

    private static String TOKEN_CHECK = Constants.TOKEN_CHECK;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Around("@annotation(entranceCheck)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, EntranceCheck entranceCheck) throws Throwable {
        BaseReDto baseReDto = null;
        Object[] args = proceedingJoinPoint.getArgs();
        log.info("检验参数（已转JSON）："+ GsonUtils.parseToJson(args));
        if(args.length > 0){
            for(Object arg : args){
                if(arg instanceof BaseReDto){
                    baseReDto = (BaseReDto)arg;
                }
            }
        }
        //获取请求头数据
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        int client = 1;
        if(requestHeaderData.containsKey("client") &&
                StringUtils.checkNullAndEmpty(requestHeaderData.get("client"))){
            client = requestHeaderData.getInteger("client");
        }
        int from = 1;
        if(requestHeaderData.containsKey("from")){
            from = requestHeaderData.getInteger("from");
        }
        //是否需要检验
        if(entranceCheck.checkAuth()){
            BmsUser bmsUser = null;
            String token = requestHeaderData.getString("token");
            if(StringUtils.isBlank(token)){
                return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL,"token失效");
            }
            String USER_TOKEN_CHECK = requestHeaderData.getString("user_token_check");
            String CHECK = WebUtils.MD5(token + TOKEN_CHECK);
            String userToken = requestHeaderData.getString("userid");
            if(CHECK.equals(USER_TOKEN_CHECK)) {
                log.info("zuul网关校验通过");
                if(StringUtils.isBlank(userToken)){
                    return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL,"token失效");
                }
                baseReDto.setUserId(userToken);
            }else {
                //手动校验
                if(client == Constants.IOS_CLIENT || client == Constants.APP_CLIENT
                        || client == Constants.SMALL_PROGRAM || client == Constants.SMALL_ALI_CLIENT
                        || client == Constants.BUSINESS_MIN_APPP_CLIENT){
                    if(!(TokenUtils.checkToken(token) == TokenUtils.TOKEN_SUCCESS)){
                        return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL,"token失效");
                    }
                    baseReDto.setUserId(TokenUtils.getUserThreadLocal().get().toString());
                }else if(client == Constants.WECHAT_CLIENT){
                    if(StringUtils.isBlank(baseReDto.getOpen_id())){
                        return ResultMapHelper.result(ResultCode.CODE_ERROR_03,"缺少参数open_id");
                    }
                    Integer userId = TokenManager.getUserId(baseReDto.getOpen_id());
                    if(userId == null){
                        return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
                    }
                    baseReDto.setUserId(userId.toString());
                }
            }
            //是否被冻结
            bmsUser = TokenManager.getUser(Integer.parseInt(baseReDto.getUserId()));
            if (bmsUser == null) {
                return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL, "token失效");
            }
            //检验是否被封号
            if(from == Constants.USER_CLIENT) {
                if (bmsUser.getIsFreeze() != null && bmsUser.getIsFreeze() == Constants.COMMON_FLAG_TRUE_INT) {
                    return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL, "账号已被冻结");
                }
            }else if(from == Constants.BUSINESS_CLIENT){
                if (bmsUser.getIsFreezeBus() != null && bmsUser.getIsFreezeBus() == Constants.COMMON_FLAG_TRUE_INT) {
                    return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL, "账号已被冻结");
                }
            }
        }
        return proceedingJoinPoint.proceed(args);
    }
}
